package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileUploadController {

    @RequestMapping(value = "/fileupload")
    //参数中定义MultipartFile参数，用于接收页面提交的type=file类型的表单，要求表单名称与参数名相同
    public String fileupload(MultipartFile file, MultipartFile file1, MultipartFile file2, HttpServletRequest request) throws IOException {

        System.out.println("file upload is running ..."+file);
        //判断文件是否为空(占用空间为0)
        if(!file.isEmpty()){
            //如果大小在范围要求之类正常处理,否则抛出自定义异常
            //获取原始上传的文件名,可以当做当前文件的真是名称保存到数据库中备用
            String filename = file.getOriginalFilename();
            //设置保存路劲
            String realpath = request.getServletContext().getRealPath("/images");
            if (!new File(realpath).exists()){
                new File(realpath).mkdir();
            }
            //得到原始文件后缀
            String suffix = filename.substring(filename.lastIndexOf("."));
            //uuid作为文件的名称
            String newFileNaeme = UUID.randomUUID().toString().replaceAll("-","");
            //得到一个新文件名
            String nFileName = newFileNaeme+suffix;

            file.transferTo(new File(realpath,newFileNaeme));
        }
        return "page.jsp";
    }
}
